package core;

/*
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class HttpClient {
	
	private static final String COMPANY_WEBSITE = "http://ec2-122-248-220-35.ap-southeast-1.compute.amazonaws.com";
	private static final String QUICKTODO_DOWNLOAD_LINK = "http://ec2-122-248-220-35.ap-southeast-1.compute.amazonaws.com/QuickToDo.zip";

	public static boolean isUpdateRequired(String version) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
        	HttpResponse response;
        	HttpEntity entity;
            
            HttpPost httpost = new HttpPost(COMPANY_WEBSITE);
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("version", version));
            httpost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpost);
            
            entity = response.getEntity();
            String data = "", line;
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            while((line = br.readLine())!=null){
            	data += line;
            }
           
            if (data.startsWith("true")) {
            	return true;
            } else {
            	return false;
            }
        } catch (ClientProtocolException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
	}
	
    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
        	HttpResponse response;
        	HttpEntity entity;// = httpclient.execute(httpget);
            
        	/*
            HttpGet httpget = new HttpGet("http://ec2-122-248-220-35.ap-southeast-1.compute.amazonaws.com/?&username=alpha&password=p@55w0rd");

            HttpEntity entity = response.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            while((line = br.readLine())!=null){
            	System.out.println(line);
            }
            System.out.println("Login form get: " + response.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
			*/
        	File f = new File("data/default");
        	BufferedReader bsr = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        	String readData = "", readBuffer;
        	while((readBuffer = bsr.readLine())!=null) {
        		readData += readBuffer;
        	}
        	//System.out.println(readData);
            HttpPost httpost = new HttpPost(COMPANY_WEBSITE);/* +
                    "org=self_registered_users&" +
                    "goto=/portal/dt&" +
                    "gotoOnFail=/portal/dt?error=true");
*/
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            //nvps.add(new BasicNameValuePair("username", "alpha"));
            //nvps.add(new BasicNameValuePair("password", "p@55w0rd"));
            //nvps.add(new BasicNameValuePair("data", readData));
            nvps.add(new BasicNameValuePair("build_number", "5"));
            
            StringEntity auth = new StringEntity("username=alpha&password=p@55w0rd");
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpclient.execute(httpost);
            
            entity = response.getEntity();
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            while((line = br.readLine())!=null){
            	System.out.println(line);
            }
            
            //System.out.println("Login form get: " + response.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            /*cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
*/
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }

	public static String downloadUpdatedFile() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
        	HttpResponse response;
        	HttpEntity entity;
            
            HttpPost httpost = new HttpPost(QUICKTODO_DOWNLOAD_LINK);
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("download_update", "true"));
            
            response = httpclient.execute(httpost);
            
            entity = response.getEntity();
            if (entity != null) {
            	FileOutputStream fos = new FileOutputStream("QuickToDoUpdate.zip");
            	entity.writeTo(fos);
            	fos.close();
            	return "QuickToDoUpdate.zip";
            }
            return null;
            
        } catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }		
	}

	public static String getUpdateFileChecksum() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
        	HttpResponse response;
        	HttpEntity entity;
            
            HttpPost httpost = new HttpPost(COMPANY_WEBSITE);
            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
            nvps.add(new BasicNameValuePair("checksum", ""));
            httpost.setEntity(new UrlEncodedFormEntity(nvps));
            response = httpclient.execute(httpost);
            
            entity = response.getEntity();
            String data = "", line;
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            while((line = br.readLine())!=null){
            	data += line;
            }
            if (data.equals("")) {
            	return null;
            } else {
            	return data;
            }
        } catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
	}
    
//    public void getManifestVersion() {
//        URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class");
//        JarURLConnection conn;
//		
//        Manifest mf = null;
//		try {
//			conn = (JarURLConnection) res.openConnection();
//			mf = conn.getManifest();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        Attributes atts = mf.getMainAttributes();
//        for (Object v : atts.values()) {
//            System.out.println(v);
//        }
//    }
}